package com.hawk.eye.client.notify.publisher;

import com.hawk.eye.client.constant.HawkEyeConstant;
import com.hawk.eye.client.notify.event.AbstractConnectEvent;
import com.hawk.eye.client.notify.event.RequestDoneEvent;
import com.hawk.eye.client.notify.event.RequestFailEvent;
import com.hawk.eye.client.toolkit.HawkEyeLogger;
import com.hawk.eye.common.core.ApiResult;
import com.hawk.eye.common.model.ServiceAuthData;
import com.hawk.eye.common.utils.Kv;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

/**
 * @className: HawkEyePublisher
 * @description:
 * @author: salad
 * @date: 2023/2/28
 **/
@Slf4j
public class HawkEyePublisher implements ApplicationEventPublisherAware {

    private static ApplicationEventPublisher publisher;

    public static void publishEvent(ApiResult<ServiceAuthData> result, Boolean firstConnect) {

        Kv kv = Kv.create().set(HawkEyeConstant.RESULT, result)
                .set(HawkEyeConstant.FIRST_CONNECT, firstConnect);
        AbstractConnectEvent connectEvent;
        //根据响应是否成功而发布不同事件
        if (result.getCode() == ApiResult.SUCCESS) {
            connectEvent = new RequestDoneEvent(kv);
        } else {
            connectEvent = new RequestFailEvent(kv);
        }
        HawkEyePublisher.publish(connectEvent);
    }

    public static void publish(AbstractConnectEvent event) {
        if (publisher != null) {
            try {
                publisher.publishEvent(event);
            } catch (Exception e) {
                HawkEyeLogger.errorWithSkipSend(HawkEyePublisher.class, "HawkEyeClient发布连接事件失败：["+event.getClass().getSimpleName()+"]", e);
            }
        }
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
        HawkEyePublisher.publisher = publisher;
    }

}
